package com.jzqf.harmonydemo.utils.file;

import com.jzqf.harmonydemo.utils.LogUtil;
import okhttp3.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件下载
 *
 * @author LiuWeiHao
 * 2021/5/20 16:37
 */
public class DownloadFile {
    /**
     * 下载文件
     *
     * @param url        文件绝对路径
     * @param parentPath 父级目录的路径
     */
    public static void downloadFile(String url, String parentPath) {
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        final long startTime = System.currentTimeMillis();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Connection", "close")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                // 储存下载文件的目录
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    LogUtil.d("upload", "total=" + response.body().contentLength());
                    saveFile(is, parentPath + "/" + fileName);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    /**
     * 将输入流写入到本地文件
     *
     * @param inputStream  输入流
     * @param absolutePath 本地绝对路径
     */
    public static boolean saveFile(InputStream inputStream, String absolutePath) throws IOException {
        File file = new File(absolutePath);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte[] buffer = new byte[4 * 1024];
        int length;
        long sum = 0;
        while ((length = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, length);
            sum += length;
            LogUtil.d("saveFile", "sum=" + sum);
        }
        LogUtil.d("saveFile", "下载完成了");
        fileOutputStream.flush();
        fileOutputStream.close();
        return true;
    }

}
